package com.librarySystem.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.librarySystem.dto.RecordDTO;
import com.librarySystem.entity.Book;
import com.librarySystem.entity.Record;

@Repository
public class RecordDao implements RecordDaoInterface {
	@Resource
	private SessionFactory sessionFactory;

	@Override
	public List<Record> find(RecordDTO recordDTO) {

		// List<?> result = this.sessionFactory.getCurrentSession()
		// .createQuery("from Record r where r.book.bookNo = :bookNo")
		// .setParameter("bookNo", recordDTO.getBookNo()).list();
		Session session = this.sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(Record.class, "r").createAlias("r.book", "book");
//		Criteria criteria = session.createCriteria(Record.class).createCriteria("book");
		if (recordDTO.getBookNo() > 0) {
			criteria.add(Restrictions.eq("book.bookNo", recordDTO.getBookNo()));
//			criteria.add(Restrictions.eq("bookNo", recordDTO.getBookNo()));
		}
		if (recordDTO.getOperateType() > 0) {
			criteria.add(Restrictions.eq("operateType",
					recordDTO.getOperateType()));
		}
		List<?> result = criteria.list();
		if (result != null && result.size() > 0) {
			return (List<Record>) result;
		}
		return null;
	}

	@Override
	public boolean save(Record record) {
		return (Integer) sessionFactory.getCurrentSession().save(record) > 0;
	}

}
